﻿using System;

namespace TypeScriptJson.Generator
{
	public abstract class TypeMapping
	{
		protected string CustomModuleName;
		protected string CustomTypeName;

		public Type UnderlyingType { get; private set; }

		public abstract bool IsGenerateDeclaration { get; }

		public string FileName { get; set; }

		public string ModuleName
		{
			get { return CustomModuleName ?? ModuleNameInternal; }
			set { CustomModuleName = value; }
		}

		protected virtual string ModuleNameInternal { get { return null; } }

		public string TypeName
		{
			get { return CustomTypeName ?? GetTypeNameInternal(); }
			set { CustomTypeName = value; }
		}

		public abstract string GetTypeNameInternal();

		protected TypeMapping(Type underlyingType)
		{
			UnderlyingType = underlyingType;
		}

		public abstract void WriteTypeDeclaration(TypeScriptCodeWriter codeWriter, GeneratorContext context);

		public virtual void WriteTypeReference(TypeScriptCodeWriter codeWriter, string currentModule)
		{
			if (currentModule != ModuleName && !string.IsNullOrEmpty(ModuleName))
			{
				codeWriter.Writer.Write(ModuleName);
				codeWriter.Writer.Write(".");
			}
			codeWriter.Writer.Write(TypeName);
		}

		public bool IsProcessed { get; private set; }

		public void Process(GeneratorContext context)
		{
			if (!IsProcessed)
			{
				IsProcessed = true;
				ProcessInternal(context);
			}
		}

		protected virtual void ProcessInternal(GeneratorContext context)
		{
		}
	}
}